package com.sunny.原子性.AtomicReference原子性引用;

import com.sunny.anotation.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;

@Slf4j
@NotThreadSafe
public class AtomicReferencePersonTest {
    // 请求总数
    public static int clientTotal = 500000;

    // 同时并发执行数量
    public static int threadTotal = 200000;

    // 初始化数据
    public static AtomicReference<com.sunny.原子性.AtomicReference原子性引用.Person> atomicReference = new AtomicReference<>(new com.sunny.原子性.AtomicReference原子性引用.Person(0,0, "0"));

    public static void main(String[] args) throws InterruptedException {
        // 初始化可缓存线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        // 初始化信号量
        Semaphore semaphore = new Semaphore(threadTotal);
        // 使主线程等待子线程执行完毕再执行
        CountDownLatch countDownLatch = new CountDownLatch(clientTotal);

        for(int i = 0; i < clientTotal; i++) {
            final int result = i;
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    modify(result);
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }

        countDownLatch.await();
        executorService.shutdown();
        log.info(atomicReference.get().toString());
    }

    //如果线程安全的话，age的值和name的值是一致的
    //如果线程不安全的话，age的值和name是不一样的。
    private static void modify(int i) {
        atomicReference.get().setAge(atomicReference.get().getAge() + i);
        atomicReference.get().setName(atomicReference.get().getName() + i);
        atomicReference.get().setSex(String.valueOf((Integer.parseInt(atomicReference.get().getSex()) + i)));
    }
}
